package wicket.example.components.table.test.headers;

import org.apache.commons.lang3.StringUtils;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.ajax.markup.html.repeater.data.sort.AjaxFallbackOrderByLink;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.ISortStateLocator;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;

public class SortingHeader<T> extends Panel
{

   private static final long          serialVersionUID = 1L;

   private static final String        ORDER_NONE       = "wicket_orderNone";
   private static final String        ORDER_UP         = "wicket_orderUp";
   private static final String        ORDER_DOWN       = "wicket_orderDown";

   private final T                    property;
   private final ISortStateLocator<T> stateLocator;

   public SortingHeader(final String id, final T property, final ISortStateLocator<T> stateLocator, final IModel<?> labelModel)
   {
      super(id);
      this.property = property;
      this.stateLocator = stateLocator;

      final AjaxFallbackOrderByLink<T> orderByBorder = new AjaxFallbackOrderByLink<T>("sorting", property, stateLocator)
      {

         private static final long serialVersionUID = 1L;

         @Override
         public void onClick(AjaxRequestTarget target)
         {
            String cssClass = SortingHeader.this.getCSSClass();
            this.add(new AttributeModifier("class", cssClass));
            target.add(this);
         }
      };
      String cssClass = SortingHeader.this.getCSSClass();
      orderByBorder.add(new AttributeModifier("class", cssClass));
      orderByBorder.setOutputMarkupId(true);
      orderByBorder.add(new Label("headerValue", labelModel));

      this.add(orderByBorder);
   }

   private String getCSSClass()
   {
      SortOrder sortOrder = stateLocator.getSortState().getPropertySortOrder(property);
      String result;
      switch (sortOrder)
      {
         case NONE:
         {
            result = ORDER_NONE;
            break;
         }
         case ASCENDING:
         {
            result = ORDER_UP;
            break;
         }
         case DESCENDING:
         {
            result = ORDER_DOWN;
            break;
         }
         default:
         {
            result = StringUtils.EMPTY;
            break;
         }
      }
      return result;
   }

}
